<template>
  <div class="login-container">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
      label-position="left">

      <div class="title-container">
        <h3 class="title">商户登录</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="请输入用户名" name="username" type="text"
          tabindex="1" autocomplete="on" />
      </el-form-item>

      <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
        <el-form-item prop="password">
          <span class="svg-container">
            <svg-icon icon-class="password" />
          </span>
          <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
            placeholder="请输入密码" name="password" tabindex="2" autocomplete="on" @keyup.native="checkCapslock"
            @blur="capsTooltip = false" @keyup.enter.native="handleLogin" />
          <span class="show-pwd" @click="showPwd">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
        </el-form-item>
      </el-tooltip>

      <el-button id="header-lgBtn" type="success" style="float:right;margin-bottom:30px;" @click="register()">注册</el-button>

      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
        @click.native.prevent="handleLogin">登录</el-button>

    </el-form>

    <div class="g-mask" style="display: none;">
      <div class="m-login">
        <div class="login-header">
          注册
        </div>
        <div class="login-snap">
          <div class="login-main">
            <span class="login-hint">请输入你的邮箱</span>
            <el-input size="small" type="text" class="login-input fn-mgsTop" v-model="r_email" required="true"></el-input>
            <!-- <input type="text" class="login-input fn-mgsTop"> -->
            <span class="login-hint fn-mgsTop">请输入用户名</span>
            <el-input type="text" class="login-input fn-mgsTop" v-model="r_username" required="true"></el-input>
            <span class="login-hint fn-mgsTop">请输入密码</span>
            <el-input type="password" class="login-input fn-mgsTop" v-model="r_pwd" required="true"></el-input>
            <!-- <input type="text" class="login-input fn-mgsTop"> -->
            <button type="button" class="login-btn fn-mgsTop" id="login-nextBtn">下一步</button>
          </div>
          <div class="login-main">
            <svg-icon icon-class="backBtn" class-name="login-backBtn"></svg-icon>
            <span class="login-email">
              <svg-icon icon-class="email"></svg-icon>
              <span class="fn-mgsLt">{{r_email}}</span>
            </span>
            <span class="login-hint fn-mgmTop">请输入邮箱验证码</span>
            <el-input type="text" class="login-input fn-mgsTop" v-model="r_checkCode" required="true"></el-input>
            <!-- <input type="text" class="login-input fn-mgsTop"> -->
            <button type="button" class="login-btn fn-mgmTop" id="login-onloadBtn" @click="load">登录</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import {
    validUsername
  } from '@/utils/validate'
  import SocialSign from './components/SocialSignin'
  import axios from 'axios'
  import $ from 'jquery'



  export default {
    name: 'Login',
    components: {
      SocialSign
    },
    data() {
      const validateUsername = (rule, value, callback) => {
        if (!validUsername(value)) {
          callback(new Error('请输入合法的用户名: 使用大小写字母、数字、下划线构成'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (value.length < 6) {
          callback(new Error('密码长度不得少于6个'))
        } else {
          callback()
        }
      }
      return {
        loginForm: {
          username: 'LiNing',
          password: 'lining123'
        },
        loginRules: {
          username: [{
            required: true,
            trigger: 'blur',
            validator: validateUsername
          }],
          password: [{
            required: true,
            trigger: 'blur',
            validator: validatePassword
          }]
        },
        passwordType: 'password',
        capsTooltip: false,
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {},

        is_loginPane_on:true,
        r_username:'',
        r_pwd:'',
        r_email:'',
        r_checkCode:'',
        checkCode:''
      }
    },
    watch: {
      $route: {
        handler: function(route) {
          const query = route.query
          if (query) {
            this.redirect = query.redirect
            this.otherQuery = this.getOtherQuery(query)
          }
        },
        immediate: true
      }
    },
    created() {
      // window.addEventListener('storage', this.afterQRScan)
      console.log(this.GLOBAL.mt_name);
    },
    mounted() {

      if (this.loginForm.username === '') {
        this.$refs.username.focus()
      } else if (this.loginForm.password === '') {
        this.$refs.password.focus()
      }
      const window=this;
      $("#login-nextBtn").click(function(){
        var verify = /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
        var flag=true;
        if(!verify.test(window.$data.r_email)){
          window.$message({
            message:'请输入正确的邮箱',
            type:'warning'
          })
          return;
        }
        if(window.$data.r_username.length==0){
          window.$message({
            message:'请输入用户名',
            type:'warning'
          })
          return;
        }
        if(window.$data.r_pwd.length<6){
          window.$message({
            message:'密码长度需大于等于6',
            type:'warning'
          })
          return;
        }
        axios.post('/register/checkMert',{mt_name:window.$data.r_username},{
          headers:{
            'Content-Type': 'application/json'
          }
        }).then(res=>{
          if(res.data==false){
            window.$message({
              message:'用户名已存在',
              type:'warning'
            })
            flag=false;
          }
          else{
            $(".login-snap").css({"margin-left":"-400px"});

            axios.post('/register',{email:window.$data.r_email},{
              headers:{
                'Content-Type': 'application/json'
              }
            }).then(res=>{
              console.log(res);
              window.$data.checkCode=res.data;
            })
            .catch(error=>{
              console.log("error: "+error);
            })
          }
        })
        .catch(error=>{
          console.log("error: "+error);
        })

      })
      $(".login-backBtn").click(function(){
          $(".login-snap").css({"margin-left":"0px"});
      })
      $(".g-mask").click(function(e){
          var x1=$(".m-login")[0].offsetLeft;
          var x2=x1+$(".m-login")[0].offsetWidth;
          var y1=$(".m-login")[0].offsetTop;
          var y2=y1+$(".m-login")[0].offsetHeight;
          if(e.clientX>=x1&&e.clientX<=x2&&e.clientY>=y1&&e.clientY<=y2){
              return;
          }
          $(".g-mask").fadeOut(function(){
              $(".login-snap").css({"margin-left":"0px"});
          });
          this.$data.is_loginPane_on=false;
      })
    },
    destroyed() {
      // window.removeEventListener('storage', this.afterQRScan)
    },
    methods: {
      checkCapslock(e) {
        const {
          key
        } = e
        this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        const window = this;
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true

            var mertInfo = {
              mt_name: this.$data.loginForm.username,
              mt_pwd: this.$data.loginForm.password
            }

            console.log(mertInfo);

            axios.post('/mert/check', mertInfo, {
                headers: {
                  'Content-Type': 'application/json'
                }
              }).then(res => {

                console.log(res);
                if (res.data == false) {
                  alert("用户名或者密码错误");
                  this.loading = false
                } else {
                  this.$store.dispatch('user/login', {
                      username: 'admin',
                      password: '123456'
                    })
                    .then(() => {
                      console.log(this.redirect, this.otherQuery);
                      this.$router.push({
                        path: this.redirect || '/',
                        query: this.otherQuery
                      })
                      this.loading = false
                    })
                    .catch(() => {
                      this.loading = false
                    })
                }

              })
              .catch(error => {
                console.log("error: " + error);
              })

          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      getOtherQuery(query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
      },
      check: function() {

        console.log("flag: ", flag);
        return flag;
      },
      register(){
        $(".g-mask").fadeIn();
        $(".g-mask").css({"display":"flex"});
        this.$data.is_loginPane_on=true;
      },
      load(){
        if(this.$data.r_checkCode==this.$data.checkCode){
          axios.post('/register/addMert',{mt_name:this.$data.r_username,mt_pwd:this.$data.r_pwd},{
            headers:{
              'Content-Type': 'application/json'
            }
          }).then(res=>{
            this.$message({
              message:'注册成功',
              type:'success'
            })
            $(".g-mask").fadeOut(function(){
                $(".login-snap").css({"margin-left":"0px"});
            });
            is_loginPane_on=false;
          })
          .catch(error=>{
            console.log("error: "+error);
          })
        }
        else{
          this.$message({
            message: '验证码错误',
            type: 'warning'
          })
        }
      }
    }
  }
</script>

<style lang="scss">
  $bg:#283443;
  $light_gray:#fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg:#2d3a4b;
  $dark_gray:#889aa4;
  $light_gray:#eee;


  .fn-mgsTop{
      margin-top:15px;
  }

  .fn-mgmTop{
      margin-top:25px;
  }

  .fn-mglTop{
      margin-top:35px;
  }

  .fn-mgsLt{
      margin-left:15px;
  }

  .fn-mgmLt{
      margin-left:25px;
  }

  .fn-mglLt{
      margin-left:35px;
  }



  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }

  .g-mask{
      position: fixed;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background-color: rgba(0,0,0,.7);
      z-index: 998;
      display: flex;
      justify-content: center;
      align-items: center;

      .btn-login{
          background-color: #03c47e;
          display: flex;
          width: 100px;
          height:40px;
          border-radius: 50px;
          justify-content: center;
          align-items: center;
          color:#FFFFFF;
          font-weight: bold;
          cursor: pointer;
      }
      .btn-login:hover,.login-btn:hover{
          transition: background-image 3s ease-in-out 1s;
          background-image: radial-gradient(ellipse farthest-corner at bottom,#aafced 0,#03c47e 65%);
      }
      .m-login{
          display: flex;
          flex-direction: column;
          width:400px;
          height:auto;
          color:#FFFFFF;
          border-radius: 30px;
          overflow:hidden;
      }
      .login-header{
          background-color: #304051;
          width:100%;
          padding:20px 0px;
          text-align: center;
          font-size: 18px;
      }
      .login-main{
          display: flex;
          flex-direction: column;
          justify-content: center;
          width: 400px;
          height:100%;
          padding:20px;
          background-color: #28333d;
      }
      .login-hint{
          font-size: 14px;
          color:#a5a9ac;
      }
      .login-input{
          width: 100%;
          background-color: #1E2831;
          outline: none;
          border-width: 0px;
          border-radius: 10px;
          text-indent: 0px;
          color:#FFFFFF;
          font-size: 15px;
          border: 1px solid #1E2831;
      }
      .login-input:focus{
          border: 1px solid #03C47E;
      }
      .login-btn{
          width: 100%;
          height:46px;
          font-size: 18px;
          color:#FFFFFF;
          font-weight: bold;
          text-align: center;
          background-color: #03c47e;
          outline: none;
          border: none;
          border-radius: 23px;
          cursor: pointer;
      }
      .login-backBtn{
          cursor: pointer;
      }
      .login-email{
          margin:0 auto;
          padding:10px 20px;
          text-align: center;
          background-color: #1e2831;
          font-size: 14px;
          border-radius: 20px;
          display: flex;
          align-items: center;
      }
      .login-snap{
          display: flex;

          width: 200%;
          height:365px;
          transition: margin .5s ease 0s;
      }
  }

</style>
